import * as map from './map.js';

/**
 *获取玩家位置
 *
 */
function getPlay() {
    for (var row = 0; row < map.rowNumber; row++) {
        for (var col = 0; col < map.colNumber; col++) {
            if (map.content[row][col] === map.PLAYER) {
                return {
                    row,
                    col
                }
            }
        }
    }
}

/**
 *根据玩家方向获取下个位置的row，col， value
 *left right up down四个方向
 * @param {*} row
 * @param {*} col
 * @param {*} direction
 */
function getNext(row, col, direction) {
    if (direction === 'left') {
        return {
            row: row,
            col: col - 1,
            value: map.content[row][col - 1]
        }
    } else if (direction === 'right') {
        return {
            row: row,
            col: col + 1,
            value: map.content[row][col + 1]
        }
    } else if (direction === 'up') {
        return {
            row: row - 1,
            col: col,
            value: map.content[row - 1][col]
        }
    } else if (direction === 'down') {
        return {
            row: row + 1,
            col: col,
            value: map.content[row + 1][col]
        }
    }

}

/**
 *交换位置
 *
 * @param {*} a
 * @param {*} b
 */
function exchange(a, b) {
    var temp = map.content[a.row][a.col];
    map.content[a.row][a.col] = map.content[b.row][b.col];
    map.content[b.row][b.col] = temp;
}


/**
 *判断是否胜利，箱子全部在正确位置才胜利
 *
 * @export
 * @return {*} 
 */
export function isWin() {
    for (var i = 0; i < map.correct.length; i++) {
        var p = map.correct[i];
        if (map.content[p.row][p.col] !== map.BOX) {
            return false;
        }
    }
    return true;
}


export function move(direction) {
    // 获取玩家位置
    var playPoint = getPlay();
    // 根据玩家方向获取下个位置的row，col， value
    var nextInfo = getNext(playPoint.row, playPoint.col, direction);
    // console.log(nextInfo)
    // 判断下一个位置是否是墙

    // 不是墙就移动
    if (nextInfo.value === map.SPACE) {
        exchange(playPoint, nextInfo);
        return true;
    }
    if (nextInfo.value === map.BOX) {
        // 下一位置是箱子，判断箱子下移位置是什么
        var nextNextInfo = getNext(nextInfo.row, nextInfo.col, direction);

        if (nextNextInfo.value === map.SPACE) {
            exchange(nextNextInfo, nextInfo,);
            exchange(nextInfo, playPoint);
            return true;
        }
    }

}